<script setup lang="ts">
import { onMounted, ref, nextTick } from "vue";
import { genFileId } from "element-plus";
const bgCanvas = ref(null);
const bgContext = ref(null);

const topCanvas = ref(null);
const topContext = ref(null);

const upload = ref(null);
const upload2 = ref(null);
const file = ref(null);
const file2 = ref(null);
const tempFilePath = ref(null);
const bgWidth = ref(0);
const bgHeight = ref(0);
const myFunc = () => {};
const drawBg = () => {
  const img = new Image();
  img.crossOrigin = "anonymous"; // 处理跨域图片
  img.src = tempFilePath.value;
  img.onload = async e => {
    console.log(e, img.width, img.height, "oo");
    bgWidth.value = img.width;
    bgHeight.value = img.height;
    await nextTick();
    bgContext.value.clearRect(0, 0, img.width, img.height);
    bgContext.value.drawImage(img, 0, 0, img.width, img.height);
  };
};
const fileChange = e => {
  file.value = e;
  tempFilePath.value = URL.createObjectURL(file.value.raw);
  drawBg();
};
const drawTop = (widthV, heightV) => {
  const img = new Image();
  img.crossOrigin = "anonymous"; // 处理跨域图片
  img.src = topValue.value;
  img.onload = async e => {
    width.value = widthV ? widthV : img.width;
    height.value = heightV ? heightV : img.height;
    await nextTick();
    topContext.value.clearRect(
      0,
      0,
      widthV ? widthV : img.width,
      heightV ? heightV : img.height
    );
    topContext.value.drawImage(
      img,
      0,
      0,
      widthV ? widthV : img.width,
      heightV ? heightV : img.height
    );
  };
};
const fileChange2 = async e => {
  file2.value = e;
  topValue.value = URL.createObjectURL(file2.value.raw);
  await nextTick();
  topContext.value = topCanvas.value.getContext("2d");
  drawTop();
};
const handleExceed = files => {
  upload.value!.clearFiles();
  const file = files[0];
  file.uid = genFileId();
  upload.value!.handleStart(file);
};
const handleExceed2 = files => {
  upload2.value!.clearFiles();
  const file = files[0];
  file.uid = genFileId();
  upload2.value!.handleStart(file);
};
const topValue = ref(null);
const width = ref(200);
const left = ref(0);
const top = ref(0);
const height = ref(200);
onMounted(() => {
  bgContext.value = bgCanvas.value.getContext("2d");
  document.onmouseup = () => {
    drag.value = false;
    document.onmousemove = null;
  };
});
const dleft = ref(0);
const dtop = ref(0);

const drag = ref(false);
const mousedown = event => {
  console.log(event, "摁下");
  // drag.value = true;
  let point_x = event.clientX;
  document.onmousemove = ent => {
    console.log(ent, "移动");
    let evt = ent || window.event;
    // 获取鼠标移动的坐标位置
    let ele_left = point_x - evt.clientX;
    let bl = width.value / height.value;

    width.value = width.value + ele_left;
    height.value = width.value / bl;
    drawTop(width.value, height.value);
  };
};
const mousedownLogo = event => {
  console.log(event, "摁下");
  drag.value = true;
  let point_x = event.offsetX;
  let point_y = event.offsetY;
  document.onmousemove = ent => {
    let evt = ent || window.event;
    // 获取鼠标移动的坐标位置
    let ele_left = evt.clientX - point_x;
    let ele_top = evt.clientY - point_y;
    ele_left = ele_left - 224;
    ele_top = ele_top - 166;
    if (ele_left <= 0) {
      // 设置水平方向的最小值
      ele_left = 0;
    } else if (ele_left >= bgWidth.value - width.value) {
      // 设置水平方向的最大值
      ele_left = bgWidth.value - width.value;
    }

    if (ele_top <= 0) {
      // 设置垂直方向的最小值
      ele_top = 0;
    } else if (ele_top >= bgHeight.value - height.value) {
      // 设置垂直方向的最大值
      ele_top = bgHeight.value - height.value;
    }
    // 只有鼠标按下的状态才可以移动
    if (drag.value) {
      // 将移动的新的坐标位置进行赋值
      left.value = ele_left;
      top.value = ele_top;
    }
  };
};
const saveImg = () => {
  let canvas = document.createElement("canvas");
  canvas.width = bgWidth.value;
  canvas.height = bgHeight.value;
  let context = canvas.getContext("2d");
  const img = new Image();
  img.crossOrigin = "anonymous"; // 处理跨域图片
  img.src = tempFilePath.value;
  img.onload = async e => {
    context.clearRect(0, 0, bgWidth.value, bgHeight.value);
    context.drawImage(img, 0, 0, bgWidth.value, bgHeight.value);
    const img2 = new Image();
    img2.crossOrigin = "anonymous"; // 处理跨域图片
    img2.src = topValue.value;
    img2.onload = () => {
      context.drawImage(img2, left.value, top.value, width.value, height.value);
      var dataURL = canvas.toDataURL("image/png");
      // 创建一个a标签用于下载
      var a = document.createElement("a");
      a.href = dataURL;
      a.download = `${new Date().getTime()}.png`;
      a.click();
    };
  };
  // document.body.append(canvas)
};
</script>

<template>
  <div>
    <div class="main-box">
      <div class="w-full h-[60px] flex items-center">
        <el-upload
          ref="upload"
          :show-file-list="false"
          :auto-upload="false"
          class="upload-demo"
          action="/"
          :limit="1"
          :on-exceed="handleExceed"
          @change="fileChange"
        >
          <el-button type="primary">上传底图</el-button>
        </el-upload>
        <el-upload
          ref="upload2"
          :show-file-list="false"
          :auto-upload="false"
          class="upload-demo"
          action="/"
          :limit="1"
          :on-exceed="handleExceed2"
          @change="fileChange2"
        >
          <el-button type="primary">上传上层图</el-button>
        </el-upload>
        <el-button type="primary" @click="saveImg">保存为图片</el-button>
      </div>
      <div class="w-full h-[740px] relative">
        <div class="absolute left-0 top-0 z-10">
          <canvas
            ref="bgCanvas"
            :width="bgWidth + 'px'"
            :height="bgHeight + 'px'"
          />
        </div>
        <div
          v-if="topValue"
          class="absolute z-20 cursor-move"
          :style="{
            width: width + 'px',
            height: height + 'px',
            left: left + 'px',
            top: top + 'px'
          }"
          @mousedown="mousedownLogo"
        >
          <div class="absolute left-0 top-0 w-full h-full">
            <span
              :style="{ left: dleft + 'px', top: dtop + 'px' }"
              class="border border-red-500 rounded-full w-[10px] h-[10px] absolute cursor-nesw-resize z-30"
              @mousedown.stop="mousedown"
            />
          </div>
          <canvas
            ref="topCanvas"
            :width="width + 'px'"
            :height="height + 'px'"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.main-box {
  width: 800px;
  height: 800px;
}
</style>
